import axios from 'axios'
import { Loading, Message } from 'element-ui'
import Vue from "vue";
Vue.use(Loading.directive);
Vue.prototype.$loading = Loading.service;
Vue.prototype.$message = Message;
var loading = null
//  axios 拦截器
//  ==============================================================================
const http = axios.create({
  baseURL: "http://www.ysqorz.top:8888/api/private/v1",
  //  响应时间超过报错
  timeout: '5000'
})
// 请求拦截
http.interceptors.request.use((config) => {

  loading = Vue.prototype.$loading({
    lock: true,
    text: 'Loading',
    spinner: 'el-icon-loading',
    background: 'rgba(0, 0, 0, 0.7)'
  });
  // 设置响应头                     token
  if (config.url !== '/login') {
    config.headers.Authorization = JSON.parse(window.sessionStorage.getItem('user')).token
  }
  return config
}, (err) => {
  new Promise.reject(err)
})
// 响应拦截
http.interceptors.response.use((data) => {
  loading.close();
  console.log('响应拦截的数据')
  console.log(data.data.meta);
  switch (data.data.meta.status) {
    case 200:
      Vue.prototype.$message({
        message: data.data.meta.msg,
        type: 'success'
      });
      break;
    case 201:
      Vue.prototype.$message({
        message: data.data.meta.msg,
        type: 'success'
      });
      break;
    case 204:
      Vue.prototype.$message({
        message: data.data.meta.msg,
        type: 'success'
      });
      break;

    default:
      Vue.prototype.$message({
        message: data.data.meta.msg,
        type: 'warning'
      });
      break;
  }
  return data
}, (err) => {
  console.log(err);
  new Promise.reject(err)
})
//  ==============================================================================

// 暴露模块
export function All(url, data = {}, type, params = {}) {
  return http({
    url,
    method: type,
    data,
    params
  })
}